<?php
//** VERSION 1.01 LAST UPDATE 19/07/2013 
//** For Thai Support USE UTF-8 Encoding 
//** Update : 19/07/2013 salt Payment Data Request , fsckopen
function t2p_result_test($AppCode,$AppPassword,&$errCode,$CheckIP='203.146.250.241'){
	return t2p_result($AppCode,$AppPassword,$errCode,$CheckIP);
}
function t2p_result($AppCode,$AppPassword,&$errCode,$CheckIP='203.146.250.242,54.254.132.115'){
	$ip = ipCheck();
	if(strpos($CheckIP,$ip)===false){$errCode="-1";return false;}
	$sum = '';
	$data = '';
	$result = array();
	foreach($_POST as $key=>$value){
		if($key == "Sum"){
			$sum = $value;
		}else{
			$data .=$value;		
			$result[$key]=$value;	
		}
	}
	
	if(@$result['AppCode']!=$AppCode){
		$errCode="-3";
		return false;
	}
	
	$md5 = md5($data.$AppPassword);
	if(strtolower($sum)===$md5)return $result;
	$errCode="-2";
	return false;
}

function t2p_checkout_local($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$showError = false){ 
	$url ="localhost";
	$uri ="/ibaht/api/t2p_checkout/payment_form.php";
	//$uri ="/t2p/ibaht/api/t2p_checkout/payment_form.php";
	return t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$showError,false);
}

function t2p_checkout_testdev($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$showError = false){ 
	$url ="10.10.3.23";
	$uri ="/t2p_checkout/payment_form.php";
	return t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$showError,false,82);
}

function t2p_checkout_test($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$showError = false){ 
	$url ="test-api.ibaht.com";
	$uri ="/t2p_checkout/payment_form.php";
	return t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$showError,false);
}

function t2p_checkout($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$showError = false){ 
	$url ="sec.ibaht.com";
	$uri ="/t2p_checkout/payment_form.php";
	return t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$showError);
}

function t2p_checkoutNOSSL($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$showError = false){ 
    $url ="www.ibaht.com";
    $uri ="/t2p_checkout/payment_form.php";
    //echo "TEST";
    return t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$showError,false);
}

function t2p_checkout_call($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$urlin,$uri,$showError,$isSSL=true,$port=''){  
		if($isSSL){
			$url = 'https://'.$urlin.''.$uri ;	
		}else{
			$url = 'http://'.$urlin.''.$uri ;
		}
		
		$https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
		$baseURL = $host =strtolower(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']);
		if($https){
			$baseURL = "https://".$baseURL;
		}else{
			$baseURL = "http://".$baseURL;
		}
		$reqData = "appCode=" . urlencode($AppCode) . "&appPassword=" . urlencode($AppPassword) . "&invoice=" . urlencode($InvNo) . "&amount=" . urlencode($Amount) . "&detail=" . urlencode($Detail) . "&frontUrl=" . urlencode($FrontURL); 
        $reqSalt = rand(100000,999999);
        $reqData = t2p_salt_data($reqData,$reqSalt);
		$result = "";
		if(extension_loaded('curl')){
			$data = array(
			'reqq' => $reqData);
			$data_string = "reqq=".$reqData."&CLI=PHP";//http_build_query($data);
			//echo $data_string;
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			if($port!='')curl_setopt ($ch, CURLOPT_PORT , $port);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_POST, 1 );
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false ); 
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_ENCODING, "gzip,deflate");
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
			curl_setopt($ch, CURLOPT_TIMEOUT, 15); 
			$xml_result = trim(curl_exec($ch));
			$code = curl_getinfo($ch);
			curl_close($ch);
			
			if($code['http_code'] == 200){
				if(strpos($xml_result,'000')!==false && strpos($xml_result,'000') == 0){//SUCCESS lead with 000
					$result = substr($xml_result,3);
                    if($result=="Cannot connect to database:")
                        if($showError) $result = "ไม่สามาถทำการชำระได้ ระบบกำลังปรับปรุงกรุณาติดต่อ Admin(Payment Server ขัดข้อง)";
				}else{
					 if($showError) $result = "ไม่สามาถทำการชำระได้ กำลังปรับปรุงระบบกรุณาติดต่อ Admin(Payment Server ขัดข้อง) ".$xml_result;//$xml_result;
				}
			}else{
		       if($showError) $result = "ไม่สามาถทำการชำระได้ กำลังปรับปรุงระบบกรุณาติดต่อ Admin(Cannot Connect Payment Server)";// "T2P Server Busy Or Maintainance";
			}
		
		}else{
			if(function_exists('fsockopen')) {
				$xml_result = sending_fsock($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$urlin,$uri,$isSSL);
				if(strpos($xml_result,'000')!==false && strpos($xml_result,'000') == 0){//SUCCESS lead with 000
					$result = substr($xml_result,3);
				}else{
					 if($showError) $result = $xml_result;
				}
			}else {
				if($showError) $result = "Server ไม่สนับสนุน CURL หรือ fsockopen เพื่อใช้งาน Bill Payment";
			}
		}		 
		return  preg_replace("/\r\n/",'',$result);
	}
	
	function sending_fsock($AppCode,$AppPassword,$InvNo,$Amount,$Detail,$FrontURL,$url,$uri,$isSSL){
	    $protocal="";
		if($isSSL){		
			$port = "443";
			//$url ="ssl://".$url;
			$protocal = "ssl://";// IF HTTPS Use SSL:// Leading
		}else{
			$port = "80";
		}
			
		$data_string = "appCode=" . urlencode($AppCode) . "&appPassword=" . urlencode($AppPassword) . "&invoice=" . urlencode($InvNo) . "&amount=" . urlencode($Amount) . "&detail=" . urlencode($Detail) . "&frontUrl=" . urlencode($FrontURL);
        $reqSalt = rand(100000,999999);
        $data_string = t2p_salt_data($data_string, $reqSalt);        
        $data_string="reqq=".$data_string;
		$result = httpPost( $protocal, $url , $port , $uri, $data_string);
		
		return $result;
	}
	
	function httpPost($protocal,$ip=null,$port=80,$uri=null,$content=null) {
		if (empty($ip))         { return false; }
		if (!is_numeric($port)) { return false; }
		if (empty($uri))        { return false; }
		if (empty($content))    { return false; }
		// generate headers in array.
		
		$t   = array();
         
        
        $t[] = "POST " . $uri . " HTTP/1.1";
		$t[] = "Host: ".$ip ;//. ":" . $port;
		$t[] = "User-Agent: AGENT/10.007";
		$t[] = "Content-Type: application/x-www-form-urlencoded";		
		$t[] = "Accept: text/plain";
		$t[] = "Accept: text/html";
		$t[] = "Accept-Encoding: text/html,text/plain";
		$t[] = "Content-Length: " . strlen($content);
		//$t[] = "Connection:keep-alive";
		$t[] = "Connection: close";
		$t   = implode("\r\n",$t) . "\r\n\r\n" . $content;

		//
		// Open socket, provide error report vars and timeout of 10
		// seconds.
		//
		$fp  = @fsockopen($protocal.$ip,$port,$errno,$errstr,10);
		// If we don't have a stream resource, abort.
		if (!(@get_resource_type($fp) == 'stream')) { return false; }
		//
		// Send headers and content.
		//
		// if (!fwrite($fp,$t)) {
			// fclose($fp);
			// return false;
		// }
        if(!fputs($fp,$t)){fclose($fp);return false;}
		//
		// Read all of response into $rsp and close the socket.
		//
		$rsp = '';
		while(!feof($fp)) { $rsp .= fgets($fp,8192); }
		fclose($fp);
		//
		// Call parseHttpResponse() to return the results.
		//
		return parseHttpResponse($rsp);
	}
    function t2p_salt_data($req,$salt){
        $md5 = md5($req.$salt);
        $string = base64_encode(gzcompress($req));
        $partSize = floor(strlen($string)/4); 
        return urlencode(base64_encode(gzcompress(strrev(substr($string,$partSize*1, $partSize)).substr($string,0, $partSize).strrev(substr($string,$partSize*2, $partSize))."&".$salt."_".substr($string,$partSize*3, strlen($string)-$partSize*3)."_".$md5)));               
    }
	//
	// Accepts provided http content, checks for a valid http response,
	// unchunks if needed, returns http content without headers on
	// success, false on any errors.
	//
	function parseHttpResponse($content=null) {
		if (empty($content)) { return false; }
		// split into array, headers and content.
		$hunks = explode("\r\n\r\n",trim($content));
		if (!is_array($hunks) or count($hunks) < 2) {
			return false;
		}
		// $header  = $hunks[count($hunks) - 2];
		// $body    = $hunks[count($hunks) - 1];
		// $headers = explode("\n",$header);
		
		$header = $hunks[0];
        $body = "";
        for($i=1;$i<count($hunks);$i++){
            $body.=$hunks[$i];
        }
        $header = preg_replace("/\r\n/", "\n", $header); 
        $headers = explode("\n",$header); 
        
		
		unset($hunks);
		unset($header);
		if (!validateHttpResponse($headers)) { return false; }
		if (in_array('Transfer-Coding: chunked',$headers) || in_array('Transfer-Encoding: chunked',$headers)) {
			return trim(unchunkHttpResponse($body));
		} else {
			return trim($body);
		}
	}

	//
	// Validate http responses by checking header.  Expects array of
	// headers as argument.  Returns boolean.
	//
	function validateHttpResponse($headers=null) {
		if (!is_array($headers) or count($headers) < 1) { return false; }
		switch(trim(strtolower($headers[0]))) {
			case 'http/1.0 100 ok':
			case 'http/1.0 200 ok':
			case 'http/1.1 100 ok':
			case 'http/1.1 200 ok':
				return true;
				break;
		}
		return false;
	}

	//
	// Unchunk http content.  Returns unchunked content on success,
	// false on any errors...  Borrows from code posted above by
	// jbr at ya-right dot com.
	//
	function unchunkHttpResponse($str=null) {
		if (!is_string($str) or strlen($str) < 1) { return false; }
		$eol = "\r\n";
		$add = strlen($eol);
		$tmp = $str;
		$str = '';
		do {
			$tmp = ltrim($tmp);
			$pos = strpos($tmp, $eol);
			if ($pos === false) { return false; }
			$len = hexdec(substr($tmp,0,$pos));
			if (!is_numeric($len) or $len < 0) { return false; }
			$str .= substr($tmp, ($pos + $add), $len);
			$tmp  = substr($tmp, ($len + $pos + $add));
			$check = trim($tmp);
		} while(!empty($check));
		unset($tmp);
        if(strpos($str,'>')!==false)
        if($str)$str = iconv_substr($str,0,strrpos($str,'>')+1,"UTF-8");
		return $str;
	}
	
	function ipCheck() { 
			$ip = $_SERVER['REMOTE_ADDR']; 
			return $ip;
	}
//
//   function gzdecode($data) {
//  do {
//    $tempName = uniqid('temp ');
//  } while (file_exists($tempName));
//  $tempName=pluginpath.'/t2p/'.$tempName;
//  if (file_put_contents($tempName, $data)) {
//    try {
//      ob_start();
//        @readgzfile($tempName);
//      $uncompressed = ob_get_clean();
//    } catch (Exception $e) {
//      $ex = $e;
//    }

//      unlink($tempName);

//    if (isset($ex)) {
//      throw $ex;
//    }

//    return $uncompressed;
//  }
//}

    // $data = "";

    // $data = "H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iv6jv+vP/I/+rj/tP/q7/pr/6O/66/+jv+vP+Y/+rj/4P/q7/pb/6O/6S0+qxarOm+b/AbkCYIggAAAA";
    // echo gzdecode(base64_decode($data));
    
    // $data = "ทดสอบการCompress";
    // echo base64_encode(gzcompress($data));
    
    
?>
